import wechatValidate from 'wechat-validate'
Page({
  behaviors: [wechatValidate],
  async onLoad({ point, building, room, id }) {
    this.setData({ point, building, room })
    if (id) {
      // 修改标题
      wx.setNavigationBarTitle({
        title: '编辑房屋信息',
      })
      // 获取房屋信息
      const { data: houseDetail } = await wx.http.get(`/room/${id}`)
      console.log(houseDetail)
      this.setData({ ...houseDetail })
    }
  },
  rules: {
    name: [
      { required: true, message: '姓名不能为空' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: '姓名不合法' },
    ],
    mobile: [
      { required: true, message: '手机号不能为空' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号不合法' },
    ],
    idcardFrontUrl: [{ required: true, message: '请上传正面身份证照片' }],
    idcardBackUrl: [{ required: true, message: '请上传反面身份证照片' }],
  },
  data: {
    idcardFrontUrl: '',
    idcardBackUrl: '',
    point: '',
    building: '',
    room: '',
    name: '',
    gender: 1,
    mobile: '',
  },
  changeGender(ev) {
    this.setData({ gender: ev.detail })
  },
  // 新增/修改房屋
  async goList() {
    // 1. 预校验
    if (!this.validate()) return

    delete this.data.__webviewId__
    delete this.data.status
    // 发送请求
    const { code, message } = await wx.http.post('/room', this.data)
    if (code !== 10000) return wx.utils.toast(message)
    // 3. 跳转
    wx.reLaunch({
      url: '/house_pkg/pages/list/index',
    })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
  // 选择图片
  async choose(ev) {
    console.log(ev.mark.type)
    const type = ev.mark.type // 区分正面/反面的标识
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
      })
      // 这次回显展示的是临时路径(用户体验)
      // this.setData({
      //   [type]: res.tempFiles[0].tempFilePath,
      // })
      wx.showLoading({ mask: true, title: '正在上传' })
      // 上传
      wx.uploadFile({
        url: wx.http.baseURL + '/upload',
        filePath: res.tempFiles[0].tempFilePath,
        name: 'file',
        header: {
          Authorization: `Bearer ${getApp().token}`,
        },
        success: ({ data }) => {
          // 上传成功后再替换成真实路径
          console.log({ data })
          this.setData({
            [type]: JSON.parse(data).data.url,
          })
          wx.hideLoading()
        },
      })
    } catch (error) {}
  },
})
